﻿using System.Linq.Expressions;
using B.S.DataBase.MyProject.Domain.Procurements;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using T.E.ERP.Write.API.Applicantions.Command.ProcurementsCommand;
using T.E.ERP.Write.API.Applicantions.CommandHandler.ProcurementsCommandCommand;

namespace T.E.ERP.Write.API.Applicantions.CommandHandler
{
    public class UpdReturnorderHandler : IRequestHandler<UpdReturnDtateCommand, APIResult<object>>
    {
        private readonly IBaseRepository<Preturnorder> _Preturnorder;
        private readonly ILogger<UpdReturnorderHandler> logger;

        public UpdReturnorderHandler(IBaseRepository<Preturnorder> preturnorder, ILogger<UpdReturnorderHandler> logger)
        {
            _Preturnorder = preturnorder;
            this.logger = logger;
        }

        public async Task<APIResult<object>> Handle(UpdReturnDtateCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            try
            {
                result.Code = APIEnum.修改成功;
                result.Msg = APIEnum.修改成功.ToString();
                var invoice = _Preturnorder.GetAll().Result.Where(x => x.Preturnorderid == request.Preturnorderid).FirstOrDefault();
                if (invoice == null)
                {
                    result.Code = APIEnum.操作成功;
                    result.Msg = "未找到对应的采购发票";
                    return result;
                }
                invoice.DocumentState = "审核";
                await _Preturnorder.Update(invoice);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "处理请求时发生错误");
                throw;
            }
            return await Task.FromResult(result);
        }
    }
}
